package cn.coldleaf.wiki.interceptors;

import cn.coldleaf.wiki.annotations.AuthIgnore;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @datetime 2023/10/15 下午3:18
 * @user cold
 **/
@Slf4j
public class AuthInterceptor extends AbstractInterceptor {
    public AuthInterceptor(){
        this.name = "权限拦截器";
        this.patterns = new String[]{"/**"};
    }

    private void writeError(HttpServletResponse response){
        try {
            response.sendError(HttpStatus.UNAUTHORIZED.value(),HttpStatus.UNAUTHORIZED.getReasonPhrase());
        } catch (IOException e) {
            log.error("返回错误信息失败",e);
        }
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod){
            if (((HandlerMethod) handler).getBeanType().isAnnotationPresent(AuthIgnore.class)
                    || ((HandlerMethod) handler).getMethod().isAnnotationPresent(AuthIgnore.class)){ // 忽略权限校验
                return true;
            }
            //TODO 权限校验
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }
}
